<?php

namespace App\Services;

use App\Exceptions\ApiException;
use App\Exceptions\ErrorCode;
use App\Models\BadWord;
use App\Models\SocialAccount;
use App\Models\User;
use Carbon\Carbon;
use Illuminate\Support\Facades\Cache;
use Singiu\WordBan\WordBan;

class UserService extends Service
{
    public function block($user, int $expire = 0)
    {
        $user = $this->getUser($user);
        if ($expire > 0) {
            $user->block_expired = Carbon::now()->addDay($expire);
        } else {
            $user->is_block = 1;
        }
        return $user->save();
    }

    public function changeAvatar($user, $avatar)
    {
        $user = $this->getUser($user);
        $user->avatar = $avatar;
        return $user->save();
    }

    protected function getUser($user)
    {
        $target = null;
        if ($user instanceof User) {
            $target = $user;
        } else if (is_int($user)) {
            $target = User::find($user);
        } else {
            throw new ApiException('参数 user 应该为 User 对象或整型！', ErrorCode::INVALID_PARAMATER);
        }
        if (!$target) {
            throw new ApiException('找不到用户！', ErrorCode::USER_NOT_FOUND);
        }
        return $target;
    }

    public function getUserByPhone(string $phone, string $areaCode = '+86')
    {
        $areaCode = $areaCode === '' ? '+86' : $areaCode;
        return User::where(['phone' => $phone, 'area_code' => $areaCode])->first();
    }

    public function register($data)
    {
        if (isset($data['openid']) && $data['openid'] != '') {
            $social_account = SocialAccount::where('openid', $data['openid'])->first();
            if (!$social_account) {
                throw new ApiException('参数 openid 异常，没有找到对应的社交账号信息！', ErrorCode::INVALID_PARAMATER);
            }
            $data['username'] = $social_account->nickname;
            $data['avatar'] = $social_account->avatar;
        }
        // 判断手机是否已被注册。
        $user = User::where('phone', $data['phone'])->where('area_code', $data['area_code'])->first();
        if ($user) {
            throw new ApiException('此手机已被注册！', ErrorCode::USER_REGISTED);
        }
        // 自动生成用户昵称头像资料。
        if (!isset($data['username']) || $data['username'] == '') {
            $data['username'] = '用户_' . strtolower(str_random(8));
        }
        if (!isset($data['avatar']) || $data['avatar'] == '') {
            $data['avatar'] = env('DEFAULT_AVATAR');
        }
        return User::create($data);
    }

    public function update($user, $data)
    {
        $user = $this->getUser($user);
        // 加载敏感词库。
        $bad_words = Cache::remember('bad_words', 10, function () {
            return BadWord::pluck('name')->all();
        });
        WordBan::load($bad_words);
        // 检查敏感词。
        if (isset($data['username']) && WordBan::scan($data['username'])) {
            throw new ApiException('昵称中含有不合适的字符！', ErrorCode::BAD_WORD);
        }
        return $user->update($data);
    }
}